package org.sky.sys.service;

import org.apache.logging.log4j.Logger;
import org.sky.exception.ServiceException;
import org.sky.sys.entity.SysMenu;
import org.sky.sys.entity.SysResource;
import org.sky.sys.mapper.SysCommonMapper;
import org.sky.sys.mapper.SysMenuMapper;
import org.sky.sys.mapper.SysResourceMapper;
import org.sky.sys.util.BspUtils;
import org.sky.sys.util.TreeStru;
import org.sky.util.LogUtils;
import org.sky.util.SnowflakeIdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author weifx
 * @Title: SysMenuService
 * @ProjectName springboot-platform
 * @Description: TODO{功能管理业务类}
 * @date 2019/3/6 17:42
 * @Version 1.0
 */
@Service
public class SysFunService {
    private final static Logger log = LogUtils.getLogger(SysFunService.class);
    @Autowired
    private SysMenuMapper sysMenuMapper;
    @Autowired
    private SysResourceMapper sysResourceMapper;
    @Autowired
    private SysCommonMapper sysCommonMapper;
    /**
     * 功能管理：组装功能树
     */
    public List<TreeStru> getFunctionTree(String menuCode,String isLeaf){
        List<TreeStru> list = new ArrayList();
        if("1".equals(isLeaf)){
            Example soe = new Example(SysResource.class);
            soe.createCriteria().andEqualTo("menuCode",menuCode);
            soe.setOrderByClause(" seq asc ");
            List<SysResource> solist = sysResourceMapper.selectByExample(soe);
            for(SysResource so:solist){
                TreeStru ts = new TreeStru();
                ts.setId(so.getId().toString());
                ts.setCode(so.getCode());
                ts.setText(so.getName()+"["+so.getCode()+"]");
                ts.setSeq(so.getSeq());
                ts.setIconCls("icon-resource");
                ts.setState("open");
                Map data= new HashMap();
                data.put("id", String.valueOf(so.getId()));
                data.put("code", so.getCode());
                data.put("isLeaf", "1");
                data.put("type", "resource");
                ts.setData(data);
                list.add(ts);
            }
        }else{
            Example sme = new Example(SysMenu.class);
            sme.createCriteria().andEqualTo("parentCode",menuCode);
            sme.setOrderByClause(" seq asc ");
            List<SysMenu> smlist = sysMenuMapper.selectFullFieldByExample(sme);
            for(SysMenu sm:smlist){
                TreeStru ts = new TreeStru();
                ts.setId(sm.getId().toString());
                ts.setCode(sm.getCode());
                ts.setText(sm.getName()+"["+sm.getCode()+"]");
                ts.setSeq(sm.getSeq());
                ts.setIconCls(sm.getIcon());
                ts.setState(sm.getChildCount()>0?"closed":"open");
                Map data= new HashMap();
                data.put("id", String.valueOf(sm.getId()));
                data.put("code", sm.getCode());
                data.put("isLeaf",sm.getLeafFlag());
                data.put("type", "menu");
                ts.setData(data);
                list.add(ts);
            }
        }
        return list;
    }

    /**
     * 根据Id查询菜单
     * @param id
     * @return
     */
    public SysMenu getSysMenuById(Long id){
        SysMenu sysMenu = new SysMenu();
        sysMenu.setId(id);
        return sysMenuMapper.selectOne(sysMenu);
    }

    /**
     * 根据主键查询资源
     * @param id
     * @return
     */
    public SysResource getSysResourceById(Long id){
        SysResource sysResource = new SysResource();
        sysResource.setId(id);
        return sysResourceMapper.selectOne(sysResource);
    }

    /**
     * 保存{新增/修改}菜单
     * @param sysMenu
     */
    public void saveAddEditSysMenu(SysMenu sysMenu){
        try {
            Timestamp ts = sysCommonMapper.queryTimestamp();
            if(!"1".equals(sysMenu.getLeafFlag())){
                sysMenu.setLeafFlag("0");
            }
            if (null == sysMenu.getId()) {
                Long id = SnowflakeIdWorker.getInstance().nextId();
                sysMenu.setId(id);
                sysMenu.setCreater(BspUtils.getLoginUser().getCode());
                sysMenu.setCreateTime(ts);
                sysMenu.setUpdater(BspUtils.getLoginUser().getCode());
                sysMenu.setUpdateTime(ts);
                sysMenuMapper.insertSelective(sysMenu);
            } else {
                sysMenu.setUpdater(BspUtils.getLoginUser().getCode());
                sysMenu.setUpdateTime(ts);
                Example e = new Example(SysMenu.class);
                e.createCriteria().andEqualTo("id", sysMenu.getId());
                sysMenuMapper.updateByExampleSelective(sysMenu,e);
            }
        }catch (Exception e){
            e.printStackTrace();
            log.error("菜单保存失败：{}",e.getLocalizedMessage());
            throw new ServiceException("菜单保存失败:"+e.getMessage(),e);
        }
    }
    /**
     * 保存{新增/修改}资源
     * @param sysResource
     */
    public void saveAddEditSysResource(SysResource sysResource){
        try {
            Timestamp ts = sysCommonMapper.queryTimestamp();
            if(!"1".equals(sysResource.getDefaultFlag())){
                sysResource.setDefaultFlag("0");//特殊处理Checkbox
            }
            if (null == sysResource.getId()) {
                Long id = SnowflakeIdWorker.getInstance().nextId();
                sysResource.setId(id);
                sysResource.setCreater(BspUtils.getLoginUser().getCode());
                sysResource.setCreateTime(ts);
                sysResource.setUpdater(BspUtils.getLoginUser().getCode());
                sysResource.setUpdateTime(ts);
                sysResourceMapper.insertSelective(sysResource);
            } else {
                sysResource.setUpdater(BspUtils.getLoginUser().getCode());
                sysResource.setUpdateTime(ts);
                Example e = new Example(SysResource.class);
                e.createCriteria().andEqualTo("id", sysResource.getId());
                sysResourceMapper.updateByExampleSelective(sysResource,e);
            }
        }catch (Exception e){
            e.printStackTrace();
            log.error("资源保存失败:{}",e.getMessage());
            throw new ServiceException("资源保存失败:"+e.getMessage(),e);
        }
    }

    /**
     * 删除菜单
     * @param code
     * @throws ServiceException
     */
    public void delSysMenuByCode(String code) throws ServiceException{
        try {
            SysMenu sysMenu = new SysMenu();
            sysMenu.setCode(code);
            sysMenuMapper.delete(sysMenu);
        }catch (Exception e){
            e.printStackTrace();
            log.error("菜单删除失败:{}",e.getMessage());
            throw new ServiceException("菜单删除失败:"+e.getMessage(),e);
        }
    }

    /**
     * 删除资源
     * @param code
     */
    public void delSysResourceByCode(String code){
        try {
            SysResource sysResource = new SysResource();
            sysResource.setCode(code);
            sysResourceMapper.delete(sysResource);
        }catch (Exception e){
            e.printStackTrace();
            log.error("资源删除失败:{}",e.getMessage());
            throw new ServiceException("资源删除失败:"+e.getMessage(),e);
        }
    }
}
